#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<unordered_map>
#include<queue>
using namespace std;
string aim = "123804765";
unordered_map<string, int> as;
string s;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
void bfs()
{
    queue<string> aq;
    aq.push(s);
    while (aq.size())
    {
        string t = aq.front();
        aq.pop();
        int pos = 0;
        while (t[pos] != '0')pos++;
        int x = pos / 3;
        int y = pos % 3;
        for (int i = 0; i < 4; i++)
        {
            int a = x + dx[i];
            int b = y + dy[i];
            if (a >= 0 && a <= 2 && b >= 0 && b <= 2)
            {
                string next = t;
                int p = a * 3 + b;
                swap(next[pos], next[p]);
                if (as.count(next))
                {
                    continue;
                }
                as[next] = as[t] + 1;
                if (next == aim)
                {
                    return;
                }
                aq.push(next);
            }
        }
    }
}
int main()
{
    cin >> s;
    bfs();
    cout << as[aim] << endl;
    return 0;
}